package com.zhuangjie.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuangjie.shop.entity.ShopSelfPickupSerialNumber;
import com.zhuangjie.shop.mapper.ShopSelfPickupSerialNumberMapper;
import com.zhuangjie.shop.service.ShopSelfPickupSerialNumberService;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuangjie
 * @since 2023-11-28
 */
@Service
public class ShopSelfPickupSerialNumberServiceImpl extends ServiceImpl<ShopSelfPickupSerialNumberMapper, ShopSelfPickupSerialNumber> implements ShopSelfPickupSerialNumberService {
    @Resource
    private Redisson redisson;

    @Override
    public Integer nextShopSelfPickupSerialNumber(Long shopId) {
        RLock lock = redisson.getLock("fetchSelfPickupSerialNumberForShop:" + shopId);
        lock.lock();
        try {
            // 取店铺序号
            LambdaQueryWrapper<ShopSelfPickupSerialNumber> queryShopSelfPickupSerialNumberWrapper = Wrappers.lambdaQuery(ShopSelfPickupSerialNumber.class)
                    .eq(ShopSelfPickupSerialNumber::getShopId, shopId);
            ShopSelfPickupSerialNumber shopSelfPickupSerialNumber = this.baseMapper.selectOne(queryShopSelfPickupSerialNumberWrapper);
            if (shopSelfPickupSerialNumber == null || !LocalDate.now().equals(shopSelfPickupSerialNumber.getLastGenDate())) {
                // 新的一天
                if (shopSelfPickupSerialNumber == null) shopSelfPickupSerialNumber = new ShopSelfPickupSerialNumber();
                shopSelfPickupSerialNumber.setShopId(shopId);
                shopSelfPickupSerialNumber.setLastGenDate(LocalDate.now());
                shopSelfPickupSerialNumber.setQueueSequenceNumber(1); // 取餐号从1开始
            }else {
                // 递加
                shopSelfPickupSerialNumber.setQueueSequenceNumber(shopSelfPickupSerialNumber.getQueueSequenceNumber() + 1);
            }
            // 更新店铺序号
            this.saveOrUpdate(shopSelfPickupSerialNumber);
            // 新的自提序号是当前的
            return shopSelfPickupSerialNumber.getQueueSequenceNumber();
        }finally {
            lock.unlock();
        }
    }
}
